//
//  ZCStatusViewModel.swift
//  weibo
//
//  Created by Ning Xie on 16/8/12.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class ZCStatusViewModel: NSObject {

    var status:ZCStatusModel?
    //  转发数内容
    var retweetCountContent: String?
    //  评论数内容
    var commentCountContent: String?
    //  赞数内容
    var unlikeCountContent: String?
    //来源
    var sourceContent:String?
    //转发微博内容
    var retweetedContent:String?
    //会员认证
    var verifiedImage: UIImage?
    //会员等级
    var mbrankImage: UIImage?
    
    //发微博时间
    var timeAgo:String?{
        
        //  Sun Aug 14 08:37:31 +0800 2016
        
        guard let creatDateUrl = status?.created_at else{
            return nil
        }
        
        let dateFormat = NSDateFormatter()
        dateFormat.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
        dateFormat.locale = NSLocale(localeIdentifier: "en_US")
        
        let creatDate = dateFormat.dateFromString(creatDateUrl)
        
        //判断是否为今年
        if isThisYear(creatDate!) {
            
            let calender = NSCalendar.currentCalendar()
            //判断是否为今天
            if calender.isDateInToday(creatDate!)
            {
                let timeInterval = abs(creatDate!.timeIntervalSinceNow)
                
                //判断是否为刚刚
                if timeInterval <= 60 {
                    return "刚刚"
                }else if timeInterval < 3600{
                    let time = Int(timeInterval)/60
                    return "\(time)分钟前"
                }else{
                    let time = Int(timeInterval)/3600
                    return "\(time)小时前"
                }
            }
            else if calender.isDateInYesterday(creatDate!)
            {
                //时间是昨天
                dateFormat.dateFormat = "昨天 HH:mm"
            }
            else
            {
                //时间是昨天以前
                dateFormat.dateFormat = "MM-dd"
            }
            
            
        }else{
            //时间不是今年
            dateFormat.dateFormat = "yyyy-MM-dd"
        }
        
        return dateFormat.stringFromDate(creatDate!)
    }
    
    //构造方法
    init(status: ZCStatusModel) {
        super.init()
        self.status = status
        
        //设置转发,评论,赞数
        retweetCountContent = handleCount(status.reposts_count, defaultTitle: "转发")
        commentCountContent = handleCount(status.comments_count, defaultTitle: "评论")
        unlikeCountContent = handleCount(status.attitudes_count, defaultTitle: "赞")
        
        //处理来源数据
        handleSourceContent(status.source ?? "")
        
        //处理转发微博内容
        handleRetweetedContent(status)
        
        //处理会员认证
        handleVerifiedContent(status.user?.verified_type ?? -1)
        
        //处理会员等级
        handleMbrankContent(status.user?.mbrank ?? 0)
        
        //处理微博内容的表情图片
        
        origianlAttributedString = handleEmoticonContentWithStatus(status.text!)
        
    }
    //  原创微博的富文本
    var origianlAttributedString: NSAttributedString?
    //  转发微博的富文本
    var retweetAttributedString: NSAttributedString?


    private func handleEmoticonContentWithStatus(status:String)-> NSAttributedString {
        
        let result = NSMutableAttributedString(string: status)
        
        var matchResultArray = [ZCMatchResult]()
        (status as NSString).enumerateStringsMatchedByRegex("\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]") { (matchCount, matchString, matchRange, _) in
            
            print(matchString.memory)
            if let chs = matchString.memory as? String {
                let matchResult = ZCMatchResult(matchString: chs, matchRange: matchRange.memory)
                matchResultArray.append(matchResult)
            }
        }
            for value in matchResultArray.reverse(){
                
                if let emoticon = ZCEmoticonTools.sharedZCEmoticonTools.searchEmoticonWithChs(value.matchString){
                    
                    let attributed = NSAttributedString.attributedStringWithEmoticon(emoticon, font: UIFont.systemFontOfSize(14))
                    
//                    result.replaceCharactersInRange(value.matchRange, withString: attributed)
                    result.replaceCharactersInRange(value.matchRange, withAttributedString: attributed)
                }
                
            }
        return result
    }
    
    //处理转发, 评论,赞数的逻辑
    private func handleCount(count: Int, defaultTitle: String) -> String
    {
      
        if count > 0 {
            
            if count >= 10000 {
                
                let result = CGFloat(count / 1000) / 10
                
                
                var resultStr = "\(result)万"
                //  判断字符串中是否包含0
                if resultStr.containsString(".0") {
                    
                    resultStr = resultStr.stringByReplacingOccurrencesOfString(".0", withString: "")
                }
                return resultStr
                
            } else {
                return "\(count)"
            }
            
        } else {
            
            return defaultTitle
        }
    }
    
    //处理来源
    private func handleSourceContent(source:String)
    {
        if source.containsString("\">")&&source.containsString("</") {
            
            let startIndex = source.rangeOfString("\">")!.endIndex
            let endIndex = source.rangeOfString("</")!.startIndex
            
            let result = source.substringWithRange(startIndex..<endIndex)
            
            sourceContent = "来自: " + result
        }
        
    }
    
    //处理转发微博内容
    private func handleRetweetedContent(status:ZCStatusModel)
    {
        if status.retweeted_status != nil {
            
            guard let text = status.retweeted_status?.text,let name = status.retweeted_status?.user?.screen_name else{
                return
            }
            retweetedContent = "\(name): \(text)"
            
            retweetAttributedString = handleEmoticonContentWithStatus(retweetedContent!)
        }
        
    }
    
    //处理会员认证内容
    private func handleVerifiedContent(verified:Int)
    {
        //认证类型等级 -1 没有认证 ，0 认证用户，2，3，5 企业认证 ， 220 达人
        switch verified {
        case 0:
            verifiedImage = UIImage(named: "avatar_vip")
        case 2, 3, 5:
            verifiedImage = UIImage(named: "avatar_enterprise_vip")
        case 220:
            verifiedImage = UIImage(named: "avatar_grassroot")
        default:
            verifiedImage = nil
        }
        
    }
    
    //处理会员等级内容
    private func handleMbrankContent(mbrank:Int)
    {
        
        if mbrank > 0 && mbrank <= 6 {

            mbrankImage = UIImage(named:"common_icon_membership_level\(mbrank)")
        }else if mbrank == 0 {
            
            mbrankImage = UIImage(named:"common_icon_membership")
        }
        else{
            mbrankImage = nil
        }
    }
    
    //判断创建年份是否为今年
    private func isThisYear(creatDate:NSDate)->Bool
    {
        
        let format = NSDateFormatter()
        format.dateFormat = "yyyy"
        format.locale = NSLocale(localeIdentifier: "en_US")
        
        //创建的年份
        let creatDateYear = format.stringFromDate(creatDate)
        //当前的年份
        let currentDateYear = format.stringFromDate(NSDate())
        
        //是否相等
        return creatDateYear == currentDateYear
        
    }
    
    
    
    
    
    
    
    
    
    
    
    
}
